﻿
namespace KingerRobot.MexicoSailunMDC.Biz;
/// <summary>
///  入库扫描仪任务创建
///  2025-05-06 新增全景扫码器扫描不到胎胚条码，胎胚走环线
///  人工出库 超期胎、锁定胎 走环线
///  正常胎人工出库走异常口
/// </summary>
public class LineScannerCreateBiz : K8.MDCBB.Biz
{
    private const string ClassName = nameof(LineScannerCreateBiz);


    #region 配置参数
    private ParamData Param { get; set; }

    class ParamData
    {


        /// <summary>
        /// 扫描仪位置ID
        /// </summary>
        public long LineScannerLoc { get; set; }

    }
    #endregion

    #region PLC 通讯参数
    private ValueData Data { get; set; }
    class ValueData
    {
        /// <summary>
        /// 产品条码
        /// </summary>
        public string ProductCode { get; set; }
        /// <summary>
        /// 计数
        /// </summary>
        public long TireCount { get; set; }
        /// <summary>
        /// 读取任务号（上段线体任务读取后【有值】）才下传新任务
        /// </summary>
        public int RWorkNo { get; set; }

        public int RStatus { get; set; }

        public string ProductCode1 { get; set; }
        public string ProductCode2 { get; set; }
        public string ProductCode3 { get; set; }
        public string ProductCode4 { get; set; }
        public string ProductCode5 { get; set; }
        public string ProductCode6 { get; set; }
        public string ProductCode7 { get; set; }
        public string ProductCode8 { get; set; }
        public string ProductCode9 { get; set; }
        public string ProductCode10 { get; set; }
        public string ProductCode11 { get; set; }
        public string ProductCode12 { get; set; }
    }
    #endregion

    #region 缓存
    private CacheData Cache { get; set; }
    class CacheData
    {
        /// <summary>
        /// 计数
        /// </summary>
        public long TireCount { get; set; }

        public string ScannerProduct { get; set; }

        public string ProductCode { get; set; }
    }
    #endregion

    #region 实时日志
    private StepData Step { get; set; }
    class StepData
    {
        private string _msg = string.Empty;
        public string StepMsg
        {
            get
            {
                return this._msg;
            }
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    this._msg = string.Empty;
                    return;
                }
                this._msg = $"{ClassName}|{System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}>>{value}";
            }
        }
        public Status RStatus { get; set; }
    }
    private void StepMsg(string msg)
    {
        this.Step.StepMsg = msg;
        WriteLog(msg);
    }
    #endregion

    #region 文件日志（运行需要 Nlog 配置）
    private void WriteLog(string message)
    {
        K8.LSF.Client.Log(new K8.LSF.Log { Data = message });
    }
    #endregion 

    /// <summary>
    /// 和 PLC 通讯对象
    /// </summary>
    private BizData BizData { get; set; }

    class Status
    {
        public Status(int status)
        {
            this.HeightType = status >> 4 & 1;
        }
        public int HeightType { get; set; }
    }
    public int Execute(BizData writer)
    {
        // Excute 方法外使用 BizData
        this.BizData = writer;
        //int heightType = Value.RStatus;
        // 返回参数
        var result = 0;

        this.StepMsg($"扫码头{Param.LineScannerLoc}开始执行");
        StringBuilder sb = new StringBuilder();
        sb.Append(Data.ProductCode1);
        sb.Append(Data.ProductCode2);
        sb.Append(Data.ProductCode3);
        sb.Append(Data.ProductCode4);
        sb.Append(Data.ProductCode5);
        sb.Append(Data.ProductCode6);
        sb.Append(Data.ProductCode7);
        sb.Append(Data.ProductCode8);
        sb.Append(Data.ProductCode9);
        sb.Append(Data.ProductCode10);
        sb.Append(Data.ProductCode11);
        sb.Append(Data.ProductCode12);

        if (String.IsNullOrWhiteSpace(Data.ProductCode1) || String.IsNullOrWhiteSpace(Data.ProductCode2)
            || String.IsNullOrWhiteSpace(Data.ProductCode3) || String.IsNullOrWhiteSpace(Data.ProductCode4)
            || String.IsNullOrWhiteSpace(Data.ProductCode5) || String.IsNullOrWhiteSpace(Data.ProductCode6)
            || String.IsNullOrWhiteSpace(Data.ProductCode7) || String.IsNullOrWhiteSpace(Data.ProductCode8)
            || String.IsNullOrWhiteSpace(Data.ProductCode9) || String.IsNullOrWhiteSpace(Data.ProductCode10)
            || String.IsNullOrWhiteSpace(Data.ProductCode11) || String.IsNullOrWhiteSpace(Data.ProductCode12))
        {
            this.StepMsg($"条码信息不全");
            return result;
        }
        if (Data.ProductCode1 == "\u0000" || Data.ProductCode2 == "\u0000"
            || Data.ProductCode3 == "\u0000" || Data.ProductCode4 == "\u0000"
            || Data.ProductCode5 == "\u0000" || Data.ProductCode6 == "\u0000"
            || Data.ProductCode7 == "\u0000" || Data.ProductCode8 == "\u0000"
            || Data.ProductCode9 == "\u0000" || Data.ProductCode10 == "\u0000"
            || Data.ProductCode11 == "\u0000" || Data.ProductCode12 == "\u0000")
        {
            this.StepMsg($"条码信息不全3");
            return result;
        }

        // 获取条码
        var productCode = sb.ToString();
        // 条码为空
        if (string.IsNullOrWhiteSpace(productCode) || productCode.StartsWith(ConstFields.Default))
        {
            this.StepMsg($"{productCode}条码为空, 扫描仪{Param.LineScannerLoc}-线体任务:{Data.RWorkNo}");
            return result;
        }
        // 条码为空
        if (string.IsNullOrWhiteSpace(productCode) || productCode.Length < 12)
        {
            this.StepMsg($"{productCode}条码信息不全2");
            return result;
        }
        //if (productCode.StartsWith(ConstFields.NoRead))
        //{
        //    //productCode = ConstFields.NoRead;
        //}

        //this.StepMsg($"LineScannerCreate记录条码{productCode},缓存计数{Cache.TireCount},扫描计数{Value.TireCount}");

        //// 已扫描创建任务
        //if (Cache.TireCount == this.Value.TireCount)
        //{
        //    this.StepMsg($"第{Value.TireCount}个,没有条码/条码{productCode}任务已创建");
        //    return result;
        //}

        //// 获取条码是否已经创建
        //var barCodeService = K8.RSF.Client.Create<IScannerService>();
        //var isScanner = barCodeService.IsLogScannerByProductCode(productCode, Value.TireCount);
        //if (isScanner)
        //{
        //    Cache.TireCount = this.Value.TireCount;
        //    this.StepMsg($"{Value.TireCount}通过日志记录跟踪，条码 {productCode}任务已创建");
        //    return result;
        //}




        // 创建扫码记录
        if (Cache.ScannerProduct == productCode)
        {
            this.StepMsg($"{productCode}通过日志记录跟踪，条码 {productCode}已创建扫描记录");
            return result;
        }
        if (Cache.ProductCode == productCode)
        {
            this.StepMsg($"条码 {productCode}已创建任务");
            return result;
        }
        //var productService = K8.RSF.Client.Create<IProductService>();
        //var tireinfo = productService.GetMesProductByProductCode(productCode);

        //if (tireinfo is null)
        //{
        //    this.StepMsg($"{productCode}mes不存在");
        //    return result;
        //}


        #region 现方法
        BizTaskBean task = new();
        IWarehousingBeforeService warehousingBeforeService = K8.RSF.Client.Create<IWarehousingBeforeService>();
        var startLoc = Param.LineScannerLoc;

        var taskId = warehousingBeforeService.CreateTaskV2(startLoc, productCode);
        this.StepMsg($"扫码头{Param.LineScannerLoc}-条码{productCode},创建任务返回值{taskId}");
        if (taskId > 0)
        {
            ITaskService taskService = K8.RSF.Client.Create<ITaskService>();
            task = taskService.GetTaskBeanByProductCode(productCode);
            this.StepMsg($"异222,走Rpc方法");
            //}
            if (task is null)
            {
                this.StepMsg($"不存在未执行的入库任务");
                return result;
            }
            var mark = SetTaskInfo(task);
            if (mark > 0)
            {
                if (mark > 0)
                {
                    // 执行、保存缓存
                    //修改任务下发状态
                    taskService.UpdateTaskDown(task.TaskNo, 1);
                    this.StepMsg($"条码：{productCode},任务{task.TaskNo}- 修改状态");
                    //任务先不执行
                    var service = K8.RSF.Client.Create<IWarehousingBeforeService>();
                    service.ExecuteTask(task.TaskNo ?? 0, startLoc);
                    this.StepMsg($"条码：{productCode},任务{task.TaskNo}-执行完成");
                    Cache.ProductCode = productCode;
                }
            }
        }
        #endregion
        return result;

    }
    private int SetTaskInfo(BizTaskBean task)
    {
        var result = 0;
        var sProductCode = task.ProductCode;

        //如果是出库任务 则为直运类型 目的地plccode取指令的plccode
        string destination = task.TargetPlcLoc;
        if (task.TaskType == (int)EnumTaskType.Exwarehouse)
        {
            destination = task.TargetCmdPlcLoc;
        }

        var taskNo = task.TaskNo;
        //var outSize = task?.OutSize ?? 0;
        var groupNo = task.TaskGroup;
        this.StepMsg($"获取任务完成,task{task.ToJson()}");
        //if (string.IsNullOrWhiteSpace(destination) || string.IsNullOrWhiteSpace(sProductCode) || destination == "0" || taskNo == 0)
        //{
        //    this.StepMsg($"下传失败,参数异常{task.ToJson()}");
        //    return 0;
        //}


        try
        {
            this.StepMsg($"任务{taskNo}开始下传11111");

            if (destination.Contains("9999") || destination.Contains("8888"))
            {
                result = this.BizData.WriteData(new
                {
                    Destination = destination,        // 目标地址： 如果是异常胎下达目的地是9999,正常胎下达目的地是8888
                    WorkNo = taskNo,                   // 流水号
                    GroupId = destination,                 // 组号
                });
            }
            else
            {
                result = this.BizData.WriteData(new
                {
                    Destination = destination,        // 目标地址： 如果是异常胎下达目的地是9999,正常胎下达目的地是8888
                    WorkNo = taskNo,                   // 流水号
                    GroupId = groupNo,                 // 组号
                });
            }
               
            this.StepMsg($"任务{taskNo}下传完成,,{result}");

        }
        catch (Exception ex)
        {
            this.StepMsg($"任务{taskNo}下传失败1,参数异常{task.ToJson()}");
            return 0;

        }
        return 1;
    }
}
